package juctest;


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 江岸
 * @version V1.0
 * @ClassName: TestLock
 * @description: 同步锁
 * @date 2021/3/2011:44
 * @since V1.0
 */
public class TestLock {
    public static void main(String[] args) {
        Ticket td = new Ticket();
        new Thread(td, "窗口1").start();
        new Thread(td, "窗口2").start();
        new Thread(td, "窗口3").start();
    }
}
class Ticket implements Runnable {
    private int ticket = 100;
    private Lock lock = new ReentrantLock();//创建lock锁
    @Override
    public void run() {
        while (true) {
            //获得锁。如果锁不可用，则当前线程将被禁用以进行线程调度，并处于休眠状态，直到获取锁。
            lock.lock();
            try {
                if (ticket > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                    }
                    System.out.println(Thread.currentThread().getName() + "完成售票，余票为：" + (--ticket));
                }else {
                    break;
                }
            }finally {
                lock.unlock();
            }

        }
    }
}
